package org.web.demo.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author yexi
 */
@Slf4j
public class BackButtonFilter implements Filter {

    /**
     * 过滤器的初始化方法(在tomcat启动后调用)
     *
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("BackButtonFilter初始化");
    }

    /**
     * 作出过滤的方法
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("BackButtonFilter进行过滤操作");
        // 放行请求。将当前请求交给过滤器链继续进行过滤，直至过滤器链均已过滤完毕，最后Servlet执行service()方法。
        // TIPS:必须记得调用，否则service()方法没有执行的机会
        filterChain.doFilter(servletRequest, servletResponse);
        log.info("过滤链与Servlet的service()处理完毕，回归BackButtonFilter过滤器");
        if (servletRequest instanceof HttpServletRequest) {
            log.info("当前被BackButtonFilter处理的请求URL是: " + ((HttpServletRequest) servletRequest).getRequestURL());
            String requestURI = ((HttpServletRequest) servletRequest).getRequestURI();
            List<String> exclusions = Arrays.asList("/", "/custom_index.jsp", "/AJAXServlet", "/download");
            if (!exclusions.contains(requestURI)) {
                //因此此时做的操作是service()处理完后的追加
                servletResponse.getWriter().print("<br/><input type=\"button\" value=\"返回上一页（该按钮由过滤器提供）\" onclick=\"history.back()\">");
            }
        }
    }

    /**
     * 销毁方法
     */
    @Override
    public void destroy() {
        log.info("BackButtonFilter销毁");
    }
}